package com.example.demo1

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class LoginActivity : AppCompatActivity() {

    private val rAccount: String = "admin" // 正确的账号
    private val rPwd: String = "admin123" // 正确的密码
    private var eCount = 0 // 错误的次数

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        val edtAccount: EditText = findViewById(R.id.edtAccount)
        val edtPwd: EditText = findViewById(R.id.edtPwd)
        val btnLogin: Button = findViewById(R.id.btnLogin)
        btnLogin.setOnClickListener {
            // 模拟登录
            val account: String = edtAccount.text.toString()
            val password: String = edtPwd.text.toString()
            if (account.isBlank()) {
                Toast.makeText(this, edtAccount.hint, Toast.LENGTH_SHORT).show()
            } else if (password.isBlank()) {
                Toast.makeText(this, edtPwd.hint, Toast.LENGTH_SHORT).show()
            } else if (account != rAccount || password != rPwd) {
                Toast.makeText(this, "账号或密码错误", Toast.LENGTH_SHORT).show()
                eCount++ // 记录错误次数
                if (eCount >= 3) {
                    // 错误3次，跳转只验证界面
                    startActivityForResult(Intent(this, MainActivity::class.java), 100)
                }
            } else {
                Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100 && resultCode == RESULT_OK) {
            // 验证成功，错误次数置0
            eCount = 0
        }
    }

}